import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Captcha as CaptchaEntity } from './captcha.entity';
import * as svgCaptcha from 'svg-captcha';

@Injectable()
export class CaptchaService {
  constructor(
    @InjectRepository(CaptchaEntity)
    private readonly repo: Repository<CaptchaEntity>,
  ) {}

  public async generate() {
    const captcha = svgCaptcha.create();
    const { id } = await this.repo.save({ text: captcha.text });
    return { key: id, captcha: captcha.data };
  }

  public async validate(key: string, value: string, keep = false) {
    const captcha = await this.repo.findOneOrFail(key);
    const pass = captcha.text.toLowerCase() === value.toLowerCase();
    if (!keep) await this.repo.remove(captcha);
    return pass;
  }
}
